package com.instasale.controllers;

import com.instasale.models.Seller;
import com.instasale.services.SellerService;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.webflow.engine.model.Model;

import javax.validation.Valid;
import java.util.Map;

@Controller
public class SellersController {

    private SellerService sellerService;

    public void setSellerService(SellerService sellerService) {
        this.sellerService = sellerService;
    }

    @ModelAttribute("seller")
    public Seller getSeller() {
        return new Seller();
    }

    @RequestMapping("/sellers")
    public String listSellers(Map<String, Object> map) {
        map.put("sellersList", sellerService.listSeller());
        return "sellers";
    }

    @RequestMapping(value = "/sellers/new", method = RequestMethod.GET)
    public String newSeller() {
        return "newSeller";
    }

    @RequestMapping(value = "/sellers/new", method = RequestMethod.POST)
    public String addSeller(@ModelAttribute("seller") @Valid Seller seller, BindingResult result) {
        if(result.hasErrors())
            return "newSeller";
        sellerService.addSeller(seller);
        return "redirect:/sellers";
    }

    @RequestMapping(value = "/sellers/{sellerId}", method = RequestMethod.DELETE)
    public String deleteSeller(@PathVariable("sellerId") Integer sellerId) {
        sellerService.removeSeller(sellerId);
        return "redirect:/sellers";
    }

}
